package com.yu.yupicture.aspect;

import com.yu.yupicture.annotation.AuthCheck;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import com.yu.yupicture.model.enums.UserRoleEnums;
import com.yu.yupicture.model.domain.entry.User;
import com.yu.yupicture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class authAspect {
    /**
     * 拦截用户权限
     */

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //1：从注解获取信息
        String auth = authCheck.value();
        UserRoleEnums userRoleEnums1 = UserRoleEnums.getByValue(auth);
        //2：如果 auth 为空，则直接放行
        if(userRoleEnums1==null){
            return joinPoint.proceed();
        }
        //3:获取当前登录用户信息
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User user = userService.getLoginUser(request);
        if(user == null){
            throw new biusnessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //获取用户权限
        UserRoleEnums userRoleEnums = UserRoleEnums.getByValue(user.getUserRole());
        if(userRoleEnums == null){
            throw new biusnessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
        }
        if(!userRoleEnums1.equals(userRoleEnums)){
            throw new biusnessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
        }
        return joinPoint.proceed();
    }
}
